<?php
Cinnamon::loadClass('UIComponent');
Cinnamon::loadClass('IFilter');
Cinnamon::loadClass('DatabaseCollection');

class DatabaseFilter extends UIComponent implements IFilter {
	
	/**
	 * Creates an instance of DatabaseFilter
	 */
	public function __construct($title, $table, $field, $data=null) {
		parent::__construct($id);
		
		// register properties
		$this->registerProperties('table', 'field', 'data', 'selected', 'any');
		
		// initialize properties
		$this->title = $title;
		$this->table = $table;
		$this->field = $field;
		$this->any 	 = true;
		$this->selected = null;
		if ( $data == null ) {
			$this->data = new DatabaseCollection(Cinnamon::registry('db'), $table, 
						'DISTINCT '. $field .' AS label, '. $field .' AS value');
			$this->data->filter($field .' <> ?', null)->filter($field .' IS NOT NULL')->sort($field);
		} else {
			$this->data	 = $data;
		}
	}
	
	/**
	 * @see IFilter::filter()
	 */
	public function filter($collection) {
		if ( $collection instanceof DatabaseCollection ) {
			if ( strcasecmp($collection->getTable(), $this->table) == 0 && $this->selected->value != null ) {
				$collection->filter($this->table .'.'. $this->field .'= ?', $this->selected->value);
			}
		}
	}
	
	/**
	 * @see UIComponent::render()
	 */
	public function render() {
		Cinnamon::loadClass('Text');
		$text = new Text();
		
		$name 	= 'filters_'. strtolower($this->id);
		echo '<p><label for="'. $name .'">'. $this->title .':</label>';
		echo '<select name="'. $name .'" id="'. $name .'">';
		if ( $this->any ) {
			$selected = ( $item->selected->value == null ) ? ' selected="selected"' : '';
			echo '<option value=""'. $selected .'>Any</option>';
		}
		
		$selectedValue = $this->selected->value;
		foreach ( $this->data as $item ) {
			$selected = ( $item->value == $selectedValue && ( $item->value != null || !$this->any ) ) ? ' selected="selected"' : '';
			echo '<option value="'. $item->value .'"'. $selected .'">'. $text->summarize($item->label,30,'...') .'</option>';
		}
		echo '</select></p>';
	}
	
	public function __get($name) {
		if ( $name == 'selected' ) {
			// get value from registry
			$value = Cinnamon::registry('session')->get('filters.'. strtolower($this->id));
			
			if ( $this->properties['selected'] == null && $this->any == true && empty($value) ) {
				$item->value = null;
				$item->label = 'Any';
				$this->properties['selected'] = $item;
			} else if ( $this->properties['selected'] == null ) {
				// search if the current value exists!
				foreach ( $this->data as $item ) {
					if ( $item->value == $value ) {
						$this->properties['selected'] = $item;
					}
				}
				// if not, select the first available value
				if ( $this->properties['selected'] == null ) {
					$this->data->rewind();
					$this->properties['selected'] = $this->data->current();
				}		
			}
			return ( $this->properties['selected'] );	
		}
		return parent::__get($name);
	}
}

?>